package com.fahai.web.controller;

import com.fahai.common.PageVo;
import com.fahai.common.PropertyPlaceholder;
import com.fahai.utils.DateUtil;
import com.fahai.utils.json.JsonResult;
import com.fahai.web.entity.BusPayFlowno;
import com.fahai.web.entity.DeviceInfo;
import com.fahai.web.service.ConvenientService;
import com.fahai.web.service.DeviceService;
import org.apache.commons.httpclient.HttpStatus;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.jsoup.Jsoup;
import org.jsoup.UnsupportedMimeTypeException;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.net.URLEncoder;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;

import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 设备管理
 */

@Controller
@RequestMapping("/device")
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class DeviceController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(DeviceController.class);

    @Autowired
    DeviceService deviceService;
    @Value("#{system.Appid}")
    public String Appid;
    @Value("#{system.Secret}")
    public String Secret;
    /**
     * 返回界面
     * @param model
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','设备管理-0','设备管理-1')")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String enterCallPage(Model model){
        model.addAttribute("selectTab","设备管理");
        return "device_manage";
    }

    /**
     * 查看通话记录列表
     * @param pageVo
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','设备管理-0','设备管理-1')")
    @ResponseBody
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    public JsonResult findCallRecordList(PageVo pageVo, Model model, DeviceInfo deviceInfo) throws Exception {

        if(null!=deviceInfo.getStartTimeTo()&&deviceInfo.getStartTimeTo()!=""){
            deviceInfo.setStartTimeTo(deviceInfo.getStartTimeTo()+" 23:59:59");
        }
        PageVo pageVoData = deviceService.findList(deviceInfo,pageVo);
        return ok("获取设备管理数据",pageVoData);
    }

    /**
     * 分页总数
     *
     * @param model
     * @return
     * @throws IOException
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','设备管理-0','设备管理-1')")
    @ResponseBody
    @RequestMapping(value = "/count", method = RequestMethod.POST)
    public JsonResult listcount(PageVo pageVo, Model model, DeviceInfo deviceInfo) throws IOException {



        if(null!=deviceInfo.getStartTimeTo()&&deviceInfo.getStartTimeTo()!=""){
            deviceInfo.setStartTimeTo(deviceInfo.getStartTimeTo()+" 23:59:59");
        }
        int count= deviceService.getCount(deviceInfo, pageVo);
        pageVo.setTotal( Long.valueOf(count));
        model.addAttribute("count", pageVo);
        return ok("查询", pageVo.getTotal());
    }


    public String  getToken( DeviceInfo deviceInfo){
       // String APPID = "wx27aa6e7fdecfd385";
      //  String SECRET = "7127f892256df8b7eec1e6a6af2c5013";
        String access_token = "";
        String aturl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Appid
                + "&secret=" + Secret;
        try {
            //已经过时的方法
//            DefaultHttpClient client = new DefaultHttpClient();
//            HttpGet request = new HttpGet(aturl);
//            HttpResponse response = client.execute(request);
            //建议使用新方法
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(aturl);
            CloseableHttpResponse response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String strResult = EntityUtils.toString(response.getEntity());
               System.out.println("get请求结果:" + strResult);
                JSONObject jsonResult = new JSONObject(strResult);
                 access_token = (String) jsonResult.get("access_token");
                System.out.println("get请求结果   access_token  :   " + access_token);
            } else {
          // System.out.println("get请求提交失败:" + access_token_url);
            }

        } catch (IOException e) {
         // System.out.println("get请求提交失败:" + access_token_url + e);
        }
        return access_token;
    }


    public byte[] GetPostUrl(String access_token,String id) throws Exception {
        String result = null;
        byte[] in_b=null;
        String json="{\"scene\":\""+id+"\"}";
        String url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;
        // 将JSON进行UTF-8编码,以便传输中文
        String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        StringEntity se = new StringEntity(json);
        se.setContentType("application/json");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        httpPost.setEntity(se);
        CloseableHttpResponse response = httpclient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                InputStream instreams = resEntity.getContent();
                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                byte[] buff = new byte[100]; //buff用于存放循环读取的临时数据
                int rc = 0;
                while ((rc = instreams.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                in_b = swapStream.toByteArray(); //in_b为转换之后的结果
            }
        }
        return in_b;
    }







    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResult add(DeviceInfo deviceInfo) throws Exception {
        if  (deviceInfo.getDeviceDateStr()!=null && deviceInfo.getDeviceDateStr()!=""){
            deviceInfo.setDeviceDate(DateUtil.StringToTimeStamp(deviceInfo.getDeviceDateStr(),"yyyy-MM-dd"));
        }
        if  (deviceInfo.getDeviceUpdateStr()!=null && deviceInfo.getDeviceUpdateStr()!=""){
            deviceInfo.setDeviceUpdate( DateUtil.StringToTimeStamp(deviceInfo.getDeviceUpdateStr(),"yyyy-MM-dd"));
        }
        String access_token= getToken(deviceInfo);
        byte[] in_b=  GetPostUrl(access_token,deviceInfo.getDeviceNum());
        deviceInfo.setDeviceUrl(in_b);
        deviceService.insert(deviceInfo);
        return ok("添加成功");
    }
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResult update(DeviceInfo deviceInfo)  throws Exception {

      if  (deviceInfo.getDeviceDateStr()!=null && deviceInfo.getDeviceDateStr()!=""){
          deviceInfo.setDeviceDate(DateUtil.StringToTimeStamp(deviceInfo.getDeviceDateStr(),"yyyy-MM-dd"));
      }
      if  (deviceInfo.getDeviceUpdateStr()!=null && deviceInfo.getDeviceUpdateStr()!=""){
          deviceInfo.setDeviceUpdate( DateUtil.StringToTimeStamp(deviceInfo.getDeviceUpdateStr(),"yyyy-MM-dd"));
      }
        String access_token= getToken(deviceInfo);
        byte[] in_b=  GetPostUrl(access_token,deviceInfo.getDeviceNum());
        deviceInfo.setDeviceUrl(in_b);
        deviceService.update(deviceInfo);
        return ok("修改成功");
    }
   @ResponseBody
    @RequestMapping(value = "/ewmurl", method = RequestMethod.GET)
    public JsonResult ewmurl(HttpServletRequest request, HttpServletResponse resp, DeviceInfo deviceInfo) throws IOException {
       //字节码转流
       if(null==deviceInfo.getDeviceNum()||deviceInfo.getDeviceNum()==""){
           return null;
       }
        DeviceInfo vo =deviceService.getDeviceInfoByDeviceNum(deviceInfo);
       if(null==vo.getDeviceUrl()){
           return null;
       }
          ByteArrayInputStream is = new ByteArrayInputStream(vo.getDeviceUrl());

       resp.setCharacterEncoding("UTF-8");
       resp.setContentType("application/x-download");
       resp.setContentType ("image/JPEG");
       resp.addHeader("Content-Disposition", "attachment;filename=" + "ewm.jpeg");
       //流传入前台
       OutputStream out = resp.getOutputStream();
       out.write(vo.getDeviceUrl());
       out.flush();
       out.close();
       return ok("加载成功");
    }












}
